<?php

namespace app\admin\model;

use think\Model;
use app\common\model\ScoreLog;
use addons\epay\library\Service;


class Withdraw extends Model
{

    

    

    // 表名
    protected $name = 'withdraw';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'status_text'
    ];

    public function getOriginData()
    {
        return $this->origin;
    }
  
     protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            $orgin = $row->getOriginData();
            
            if ($changed['status'] == 2) {#如果是拒绝，就要把水滴还回去
                 $user = User::find($orgin['user_id']);
                 $otherConfig = Otherconfig::find(1);
                 $orginWaterNum =  $orgin['money'] / $otherConfig['change'];
                 $user->num = $user->num + $orginWaterNum;
                 $user->save();
                 ScoreLog::insert(['createtime' => time(),'user_id' => $orgin['user_id'],'before' => $user['num'],'score' =>  $orginWaterNum,'after' => $user->num,'memo' => '提现拒绝返现','status' => 0]);
            }
            $row->admin_id = session('admin.id');
               
        });
    }

    public function getStatusList()
    {
        return ['0' => __('待审核'), '1' => __(' 通过'), '2' => __('拒绝')];
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
